/*================================================================
*   Copyright (C) 2020 belonging to YangZhengQing. All rights reserved.
*   
*   文件名称：shared_mem_create.c
*   创 建 者：YangZhengQing
*   创建日期：2020年03月11日
*   描    述：
*
*================================================================*/


//#include "shared_mem_create.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/time.h>

#define FTOK_PATH "../apue"
#define PROJ_ID 10

//定义共享结构体
typedef struct
{
	int			money;
	char		ID[6];
}bank_card_t;

void seconds_delay(unsigned seconds)
{
	struct timeval tv;
	tv.tv_sec=seconds;
	tv.tv_usec=0;
	int err;
	do{
		err=select(0,NULL,NULL,NULL,&tv);
	}while(err<0 && errno==EINTR);
}



int main(int argc, char **argv)
{
	key_t			key = -1;
	bank_card_t		*b_card;//银行卡
	int				shmid = -1;//内存ID
	int				i ;

	key = ftok(FTOK_PATH, PROJ_ID);//获取身份证
	if(key < 0)
	{
		printf("ftok error:%s\n",strerror(errno));
		exit(0);
	}

	shmid = shmget(key, sizeof(bank_card_t), IPC_CREAT|0666);//分配共享内存
	if(shmid < 0)
	{
		printf("shmget error:%s\n",strerror(errno));
		exit(0);
	}

	b_card = shmat(shmid, NULL, 0);//启动共享内存并由系统选择共享内存地址，且连接到当前进程的地址空间
	if(b_card == (void *)-1)
	{
		printf("shmat error:%s\n",strerror(errno));
		exit(0);
	}


	for(i = 0; i < 4; i++)
	{
		printf("账号:%s			余额:%d\n",b_card->ID,b_card->money);
		seconds_delay(2);
	}

	if(shmdt(b_card) < 0)//从当前进程分离共享内存
	{
		printf("shmdt error:%s\n",strerror(errno));
		exit(0);
	}

	if(shmctl(shmid, IPC_RMID, NULL))//删除共享内存
	{
		printf("shmdt error:%s\n",strerror(errno));
		exit(0);
	}

	return 0;


}
